package lib.streamapi;

import dto.Article;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * stream filter
 */
public class ArtileMethod {

    public Article getFirstJavaArticle(List<Article> articles) {
        for (Article article : articles) {
            if (article.getTags().contains("Java")) {
                return article;
            }
        }
        return null;
    }

    public Optional<Article> getFirstJavaArticleStream(List<Article> articles) {
        return articles.stream().filter(article ->
                article.getTags().contains("java")).findFirst();
    }

    public List<Article> getAllJavaArticle(List<Article> articles) {
        List<Article> result = new ArrayList<>();
        for (Article article : articles) {
            if (article.getTags().contains("java")) {
                result.add(article);
            }
        }
        return result;
    }

    public List<Article> getAllJavaArticlesStream(List<Article> articles) {
        return articles.stream().filter(article ->
                article.getTags().contains("java")).collect(Collectors.toList());
    }

    public Map<String, List<Article>> groupByAuthor0(List<Article> articles) {
        Map<String, List<Article>> result = new HashMap<>();
        for (Article article : articles) {
            if (result.containsKey(article.getAuthor())) {
                result.get(article.getAuthor()).add(article);
            } else {
                ArrayList<Article> temp = new ArrayList<>();
                temp.add(article);
                result.put(article.getAuthor(), temp);
            }
        }
        return result;
    }

    public Map<String, List<Article>> groupByAuthor(List<Article> articles) {
        return articles.stream().collect(Collectors.groupingBy(Article::getAuthor));
    }

    public Set<String> getDistinctTags(List<Article> articles) {
        Set<String> result = new HashSet<String>();
        for (Article article : articles) {
            result.addAll(article.getTags());
        }
        return result;
    }

    public Set<String> getDistinctTagsStream(List<Article> articles) {
        return articles.stream().flatMap(article
				-> article.getTags().stream()).collect(Collectors.toSet());
    }
}
